package com.prj.ufdm.web.config;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.MultipartConfigElement;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.prj.ufdm.web.security.ScyConstants;

@Configuration
public class WebConfig implements WebMvcConfigurer {
	
	@Resource
	private Environment env;
	
	
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/")
                .addResourceLocations("classpath:/resources/");
    }
    
	@Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); 
        return new CorsFilter(source);
    }
    
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); 
        corsConfiguration.addAllowedHeader("*"); 
        corsConfiguration.addAllowedMethod("*"); 
        return corsConfiguration;
    }
    
	/**
	  * 使用 FastJson 
	 * @return
	 */
	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters() {
        // 定义一个转换消息的对象
		FastJsonHttpMessageConverter fastConverter4 = new FastJsonHttpMessageConverter();
		// 配置信息
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
		
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        // 媒体类型
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		// 在转换器中添加配置信息
		fastConverter4.setFastJsonConfig(fastJsonConfig);
		fastConverter4.setSupportedMediaTypes(fastMediaTypes);
		return new HttpMessageConverters(fastConverter4);
	}   
	
	/**  
          * 文件上传配置  
     * @return  
     */  
    @Bean  
    public MultipartConfigElement multipartConfigElement() {  
        MultipartConfigFactory factory = new MultipartConfigFactory();  
        factory.setMaxFileSize(DataSize.of(100, DataUnit.MEGABYTES));
        factory.setMaxRequestSize(DataSize.of(100, DataUnit.MEGABYTES));
        return factory.createMultipartConfig();  
    }  
    
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
    
	@Bean
	public String initConfigParam() {
		String extraAllowUrl = env.getProperty("auth.alllow.url");
		try {
			if(extraAllowUrl!=null && !extraAllowUrl.equals("")) {
				ScyConstants.AUTH_ALLLOW_URL = ScyConstants.AUTH_ALLLOW_URL + "," + extraAllowUrl;
			}
		}
		catch(Exception er) {
			
		}
		String tokenValidMinutes = env.getProperty("token.valid.minutes");
		try {
			if(tokenValidMinutes!=null && !tokenValidMinutes.equals("")) {
				ScyConstants.TOKEN_VALID_MINUTES = Integer.parseInt(tokenValidMinutes);
			}
		}
		catch(Exception er) {
			
		}
		return "";
	}
}
